package com.glaciervirtualdevice.service.Impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.glaciervirtualdevice.Generator.*;
import com.glaciervirtualdevice.entity.VirtualDevice;
import com.glaciervirtualdevice.constant.DataConstant;
import com.glaciervirtualdevice.dto.THDateDTO;

import com.glaciervirtualdevice.mapper.VitrualDeviceMapper;
import com.glaciervirtualdevice.quart.WarmHumidQuartz;
import com.glaciervirtualdevice.service.VitrualDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import static com.glaciervirtualdevice.constant.DataConstant.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Sun
 * @DateTime: 2025/4/1 17:46
 * @Description:
 **/
@Service
public class VitrualDeviceServiceImpl implements VitrualDeviceService {
    @Autowired
    private VitrualDeviceMapper vitrualDeviceMapper;
    @Autowired
    private WarmHumidQuartz warmHumidQuartz;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 创建一个仪表硬件
     *
     * @return
     */
    @Override
    public Boolean createDevice() {
        VirtualDevice vitrualDevice = new VirtualDevice();
        vitrualDevice.setSn(SnGenerator.getSn());

        vitrualDevice.setMaxHum(HumidityGenerator.getMaxHumidity());
        vitrualDevice.setMinHum(HumidityGenerator.getMinHumidity());
        vitrualDevice.setStandardHum(HumidityGenerator.getStableHumidity());
        vitrualDevice.setMinTem(TemperatureGenerator.getMinTemperature());
        vitrualDevice.setMaxTem(TemperatureGenerator.getMaxTemperature());
        vitrualDevice.setStandardTem(TemperatureGenerator.getStandardTemperature());
        vitrualDevice.setState(DataConstant.ZERO);
        vitrualDevice.setToken(TokenGenerator.getToken());
        vitrualDevice.setGapTime(CronGenerator.getCron());

        // 将对象转换为 Map
        Map<String, Object> deviceMap = JSON.parseObject(JSON.toJSONString(vitrualDevice), Map.class);
        BoundHashOperations<String, Object, Object> ops = stringRedisTemplate.boundHashOps(vitrualDevice.getSn());
        // 存储到 Redis
        for (Map.Entry<String, Object> entry : deviceMap.entrySet()) {
            ops.put(entry.getKey(), entry.getValue().toString());
        }

        // 启动任务
        warmHumidQuartz.startDevice(vitrualDevice.getSn(), vitrualDevice.getStandardTem(), vitrualDevice.getStandardHum(), vitrualDevice.getGapTime());

        return vitrualDeviceMapper.insert(vitrualDevice) > 0;
    }

    /**
     * 检查当前设备的状态
     *
     * @param sn
     * @param token
     * @return
     */
    @Override
    public Integer checkDevice(String sn, String token) {
        QueryWrapper<VirtualDevice> wapper = new QueryWrapper<>();
        wapper.eq("sn", sn).eq("token", token);
        List<VirtualDevice> devices = vitrualDeviceMapper.selectList(wapper);
        if (!devices.isEmpty()) {
            return devices.get(0).getState();
        }
        return null;
    }

    /**
     * 删除当前设备
     *
     * @param sn
     * @param token
     * @return
     */

    @Override
    public Boolean deleteDevice(String sn, String token) {
        UpdateWrapper<VirtualDevice> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("sn", sn).eq("token", token);
        VirtualDevice device = new VirtualDevice();
        device.setState(STOP_WORD);
        int rows = vitrualDeviceMapper.update(device, updateWrapper);
        return rows > 0;
    }

    /**
     * 查询当前设备的温湿度
     *
     * @param sn
     * @param token
     * @return
     */
    @Override
    public THDateDTO getDeviceInfo(String sn, String token) {


        int maxHum = 0;
        int minHum = 0;
        int maxTem = 0;
        int minTem = 0;
        int hum = 0;
        int tem = 0;

        //查询一下当前设备是否存在且还在运行
        QueryWrapper<VirtualDevice> wapper = new QueryWrapper<>();
        wapper.eq("sn", sn).eq("token", token);
        List<VirtualDevice> devices = vitrualDeviceMapper.selectList(wapper);
        System.err.println(devices);
        if (devices.isEmpty()) {
            return null;
        }



        THDateDTO wsDate = warmHumidQuartz.getTemperatureHumidityByGroup(sn);
        if (wsDate != null) {
            //证明当前仪表有任务，直接返回温湿度
            return wsDate;
        }
        //当前仪表没任务靠开启任务
        warmHumidQuartz.startDevice(sn, devices.get(0).getStandardTem(), devices.get(0).getStandardHum(), devices.get(0).getGapTime());
        THDateDTO wsDatNev = warmHumidQuartz.getTemperatureHumidityByGroup(sn);
        System.err.println(wsDatNev);

        maxHum = devices.get(0).getMaxHum();
        minHum = devices.get(0).getMinHum();
        maxTem = devices.get(0).getMaxTem();
        minTem = devices.get(0).getMinTem();

        hum = wsDatNev.getHum();
        tem = wsDatNev.getTem();
//        当前仪表信息存到redis中
        BoundHashOperations<String, Object, Object> ops = stringRedisTemplate.boundHashOps(sn);
        ops.put("maxHum", String.valueOf(maxHum));
        ops.put("minHum", String.valueOf(minHum));
        ops.put("maxTem", String.valueOf(maxTem));
        ops.put("minTem", String.valueOf(minTem));
        ops.put("hum", String.valueOf(hum));
        ops.put("tem", String.valueOf(tem));

        return wsDatNev;

    }

    /**
     * 查询所有仪表信息
     *
     * @return
     */
//    @Cacheable("device_all_list")
    @Override
    public List<VirtualDevice> viewAllDevice() {

        return vitrualDeviceMapper.selectList(null);
    }

}
